/** biome-ignore-all lint/suspicious/noExplicitAny: ignore all */
import { BaseMigration } from "@shared/triplit/migrations/base-migration";
import type { MigrationContext } from "@shared/triplit/migrations/types";

export class EnhanceThreadMcpAssociationMigration extends BaseMigration {
  public readonly version = "2.1.0";
  public readonly description =
    "Enhance threadMcpServers with enabled and order fields for better thread-server relationship management";
  public readonly dependencies: string[] = ["1.8.0"];

  public async up(context: MigrationContext): Promise<void> {
    const { client, logger } = context;

    logger.info("Starting thread-MCP association enhancement migration");

    try {
      // Query existing threadMcpServers records
      const query = client.query("threadMcpServers");
      const result = await client.fetch(query);

      let entities: [string, any][] = [];

      if (result instanceof Map) {
        entities = Array.from(result.entries()).map(([key, value]) => [
          String(key),
          value,
        ]);
      } else if (Array.isArray(result)) {
        entities = result.map((entity) => [String(entity.id), entity]);
      } else if (result && typeof result === "object") {
        entities = Object.entries(result).map(([key, value]) => [
          String(key),
          value,
        ]);
      }

      logger.info(
        `Found ${entities.length} threadMcpServers entities to update`,
      );

      // Update existing entities to ensure they have the new fields
      for (const [id, entity] of entities) {
        const updates: any = {};

        // Add enabled field if missing (default: true)
        if (entity.enabled === undefined || entity.enabled === null) {
          updates.enabled = true;
        }

        // Add order field if missing (default: 0)
        if (entity.order === undefined || entity.order === null) {
          updates.order = 0;
        }

        if (Object.keys(updates).length > 0) {
          await client.update("threadMcpServers", id, (e: any) => {
            Object.assign(e, updates);
          });
          logger.debug(
            `Updated threadMcpServers entity ${id} with default values`,
          );
        }
      }

      logger.info(
        "Thread-MCP association enhancement migration completed successfully",
      );
    } catch (error) {
      logger.error("Failed to enhance thread-MCP association:", error);
      throw error;
    }
  }
}
